<template>
  <div class="component-marketing-distribution-item base-set">
    <el-form
      ref="dataFormRef"
      class="set-form"
      :model="dataForm"
      @submit.prevent
    >
      <!-- 基本设置 -->
      <div class="form-item">
        <div class="title">
          {{ $t('distribution.basicDistributionSet') }}
        </div>
        <div class="form-item-content">
          <!-- 分销开关 -->
          <el-form-item :label="$t('distribution.distributionSwitch')+':'">
            <el-radio-group v-model="dataForm.distributionSwitch">
              <el-radio :label="0">
                {{ $t('seckill.close') }}
              </el-radio>
              <el-radio :label="1">
                {{ $t('seckill.open') }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 业绩归属 -->
          <el-form-item :label="$t('distribution.performanceAttribution')+':'">
            <el-radio-group v-model="dataForm.attribution">
              <el-radio :label="0">
                {{ $t('distribution.paTip1') }}
                <el-tooltip
                  class="item"
                  effect="light"
                  placement="right"
                >
                  <template #content>
                    <div class="performanceAttribution-content">
                      {{ $t('distribution.promptPaTip1') }}
                    </div>
                  </template>
                  <el-icon color="#155BD4">
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
              </el-radio>
              <el-radio :label="1">
                {{ $t('distribution.paTip2') }}
                <el-tooltip
                  class="item"
                  effect="light"
                  placement="right"
                >
                  <template #content>
                    <div class="performanceAttribution-content">
                      {{ $t('distribution.promptPaTip2') }}
                    </div>
                  </template>
                  <el-icon color="#155BD4">
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 申请条件-条件审核判定 -->
          <el-form-item :label="$t('distribution.conditionalAuditJudgment')+':'">
            <el-radio-group
              v-model="dataForm.autoCheck"
              @change="changeRadio(dataForm.autoCheck)"
            >
              <el-radio :label="0">
                {{ $t('distribution.manualJudgment') }}
              </el-radio>
              <el-radio :label="1">
                {{ $t('distribution.systemJudgment') }}
              </el-radio>
              <el-radio :label="2">
                {{ $t('distribution.noAuditRequired') }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 申请条件 -->
          <el-form-item
            v-if="dataForm.autoCheck === 1"
            :label="$t('distribution.applicationConditions')+':'"
          >
            <div class="condition-item marginBottom">
              <el-checkbox
                v-model="isProd"
                class="input-checked"
              >
                {{ $t('distribution.purchaseDesignatedGoods') }}
              </el-checkbox>
              <el-button
                v-if="isProd"
                plain

                class="input-checked"
                @click="prodsSelectHandle"
              >
                {{ '选择商品' }}
              </el-button>
              <span class="tips">{{ $t('distribution.buyConditionTip2') }}</span>
              <el-row v-if="isProd">
                <div
                  v-for="(prod, index) in productVOList"
                  :key="index"
                  class="productStyle"
                >
                  <el-card
                    :body-style="{ padding: '0px' }"
                    style="height: 160px;width: 120px"
                  >
                    <ImgShow
                      :src="prod.pic"
                      :img-style="{width:'100%',height:'104px'}"
                    />
                    <div class="card-prod-bottom">
                      <span class="card-prod-name">{{ prod.prodName }}</span>
                      <el-button
                        type="text"
                        class="card-prod-name-button"
                        @click="deleteProd(index)"
                      >
                        {{ $t('user.deleteBtn') }}
                      </el-button>
                    </div>
                  </el-card>
                </div>
              </el-row>
            </div>

            <div
              class="condition-item input-group"
              :style="$t('language') === 'language' ?'marginLeft:150px':'marginLeft:72px'"
            >
              <el-checkbox
                v-model="isExpenseNumber"
                class="input-checked"
                @change="removeExpenseNumber"
              >
                {{ $t('distribution.bcTip3') }}
              </el-checkbox>
              <el-form-item prop="expenseNumber">
                <el-input
                  v-model="dataForm.expenseNumber"
                  class="input-checked"
                  type="number"
                  min="1"
                  :disabled="!isExpenseNumber"
                  style="width:240px"
                  @change="checkNumber"
                >
                  <template #append>
                    {{ $t('distribution.bcTip4') }}
                  </template>
                </el-input>
              </el-form-item>
              <span class="tips">{{ $t('distribution.bcTip5') }}</span>
            </div>

            <div
              class="condition-item input-group"
              :style="$t('language') === 'language' ?'marginLeft:150px':'marginLeft:72px'"
            >
              <el-checkbox
                v-model="isExpenseAmount"
                class="input-checked"
                @change="removeExpenseAmount"
              >
                {{ $t('distribution.dbcTip1') }}
              </el-checkbox>
              <el-form-item prop="expenseAmount">
                <el-input
                  v-model="dataForm.expenseAmount"
                  class="input-checked"
                  type="number"
                  min="0"
                  style="width:240px"
                  :disabled="!isExpenseAmount"
                  oninput="value=value.replace(/[^0-9.]/g,'')"
                  @change="checkAmount"
                >
                  <template #append>
                    {{ $t('distribution.dbcTip2') }}
                  </template>
                </el-input>
              </el-form-item>
              <span class="tips">{{ $t('distribution.dbcTip3') }}</span>
            </div>
          </el-form-item>
          <!-- 申请所需信息 -->
          <el-form-item
            v-if="dataForm.autoCheck !== 2 && paySettlementType !== 1"
            :label="$t('distribution.applyNeedInfo')+':'"
          >
            <el-checkbox v-model="dataForm.realName">
              {{ $t('distribution.realName') }}
            </el-checkbox>
            <el-checkbox v-model="dataForm.identityCardNumber">
              {{ $t('distribution.idCardNo') }}
            </el-checkbox>
            <el-checkbox v-model="dataForm.identityCardPic">
              {{ $t('distribution.idCardPhoto') }}
            </el-checkbox>
          </el-form-item>
          <!--提现发放方式-->
          <el-form-item
            v-if="paySettlementType!==1"
            :label="$t('distribution.Withdrawal')+':'"
          >
            <template #label>
              <div>
                {{ $t('distribution.Withdrawal') }}
                <el-tooltip
                  class="item"
                  effect="light"
                  :content="$t('distribution.WithdrawalTip')"
                  placement="right"
                  style="color: #155BD4;"
                >
                  <el-icon color="#155BD4">
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
                :
              </div>
            </template>
            <el-radio-group v-model="dataForm.withdrawal">
              <el-radio :label="0">
                {{ $t('distribution.Issued1') }}
              </el-radio>
              <el-radio :label="1">
                {{ $t('distribution.Issued2') }}
                <el-tooltip
                  class="item"
                  effect="light"
                  :content="$t('distribution.WithdrawalTip2')"
                  placement="right"
                  style="color: #155BD4;"
                >
                  <el-icon color="#155BD4">
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
              </el-radio>
              <el-radio :label="2">
                {{ $t('distribution.Issued3') }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
      </div>
      <!-- 提现设置 -->
      <div
        v-if="paySettlementType!==1"
        class="form-item"
      >
        <div class="title">
          {{ $t('distribution.withdrawalSettings') }}
        </div>
        <div class="form-item-content">
          <!-- 单笔提现 -->
          <el-form-item :label="$t('withdraw.eachWithdrawal')+':'">
            <el-input
              v-model.number="dataForm.amountMin"
              style="width: 180px"
              oninput="value=value.replace(/[^\d]/g,'')"
              maxlength="10"
              class="input-checked"
            >
              <template #append>
                {{ $t('distribution.dbcTip2') }}
              </template>
            </el-input>
            <span class="input-tips input-checked">,{{ $t('withdraw.tip2') }}</span>
            <el-input
              v-model.number="dataForm.amountMax"
              style="width: 180px"
              oninput="value=value.replace(/[^\d]/g,'')"
              maxlength="10"
              class="input-checked"
            >
              <template #append>
                {{ $t('distribution.dbcTip2') }}
              </template>
            </el-input>
            <span class="tips">{{ $t('withdraw.tip3') }}</span>
          </el-form-item>
          <!-- 提现频次 -->
          <el-form-item :label="$t('withdraw.withdrawalFrequency')+':'">
            <el-select
              v-model="dataForm.frequency"
              :placeholder="$t('user.pleaseSelect')"
            >
              <el-option
                :label="$t('withdraw.everyDay')"
                :value="1"
              />
              <el-option
                :label="$t('withdraw.weekly')"
                :value="7"
              />
              <el-option
                :label="$t('withdraw.monthly')"
                :value="30"
              />
              <el-option
                :label="$t('withdraw.unlimited')"
                :value="-1"
              />
            </el-select>
            <el-input
              v-if="dataForm.frequency !== -1"
              v-model.number="dataForm.number"
              style="width: 180px;"
              oninput="value=value.replace(/[^\d]/g,'')"
              maxlength="2"
              @blur="numberInpBlur"
            >
              <template #append>
                {{ $t('distribution.bcTip4') }}
              </template>
            </el-input>
          </el-form-item>
          <!-- 提现说明 -->
          <el-form-item :label="$t('withdraw.withdrawalInstructions')+':'">
            <el-input
              v-model="dataForm.paymentExplain"
              type="textarea"
              style="width: 455px"
              :rows="5"
              maxlength="50"
              show-word-limit
            />
            <br>
            <span class="tips">{{ $t('withdraw.tip4') }}</span>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <div
      class="default-btn primary-btn save"
      @click="onSubmit()"
    >
      {{ $t('distribution.save') }}
    </div>
    <prods-select
      v-if="prodsSelectVisible"
      ref="prodsSelectRef"
      :activity-type="1"
      @refresh-select-prods="selectDistributionProds"
    />
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'

const allinpayStore = useAllinpayStore()
const paySettlementType = computed(() => {
  return allinpayStore.paySettlementType
})

onMounted(() => {
  getData()
})

/**
 * 提现次数
 */
const numberInpBlur = () => {
  if (dataForm.value.number > 10) {
    dataForm.value.number = 10
  }
  if (dataForm.value.number < 1) {
    dataForm.value.number = 1
  }
}

/**
 * 获取数据
 */
const getData = () => {
  http({
    url: http.adornUrl('/platform/distributionConfig/info'),
    method: 'get',
    params: http.adornParams()
  })
    .then(({ data }) => {
      if (data !== null) {
        setDate(data)
      }
    })
}

const isProd = ref(false) // 是否指定商品
const isExpenseNumber = ref(false) // 是否指定单数
const isExpenseAmount = ref(false) // 是否指定消费
const dataForm = ref({
  distributionSwitch: 0,
  attribution: 1,
  autoCheck: 0,
  expenseNumber: null,
  prodIdList: [],
  productVOList: [],
  expenseAmount: null,
  realName: false,
  identityCardPic: false,
  identityCardNumber: false,
  frequency: null,
  amountMax: '',
  amountMin: '',
  paymentExplain: null,
  number: null,
  withdrawal: 2
})
const productVOList = ref([])
/**
 * 提交表单
 * @param data
 */
const setDate = (data) => {
  dataForm.value = data
  if (dataForm.value.productVOList == null) {
    dataForm.value.productVOList = []
  }
  dataForm.value.productVOList.forEach(el => {
    // 替换成工具方法
    checkFileUrl(el.pic)
  })
  productVOList.value = dataForm.value.productVOList
  if (dataForm.value.expenseNumber > 0) {
    isExpenseNumber.value = true
  }
  if (dataForm.value.expenseAmount > 0) {
    isExpenseAmount.value = true
  }
  if (dataForm.value.prodIdList != null && dataForm.value.prodIdList.length > 0) {
    isProd.value = true
  }
}

const dataFormRef = ref(null)
/**
 * 提交表单
 */
const onSubmit = () => {
  dataFormRef.value?.validate((valid) => {
    if (!valid) {
      return
    }
    const prodIdList = []
    if (productVOList.value && isProd.value) {
      productVOList.value?.forEach(element => {
        prodIdList.push(element.prodId)
      })
    }
    dataForm.value.prodIdList = prodIdList
    if (isProd.value && dataForm.value.prodIdList.length <= 0) {
      ElMessage({
        message: $t('marketing.pleaseSelectAProduct'),
        type: 'error',
        duration: 1500
      })
      return
    }
    if (!isProd.value) {
      dataForm.value.prodIdList = []
    }
    if (dataForm.value.expenseNumber === '.' || dataForm.value.expenseNumber === '-' || dataForm.value.expenseAmount === '.' || dataForm.value.expenseAmount === '-') {
      return
    }
    if (isExpenseNumber.value && !dataForm.value.expenseNumber) {
      ElMessage({
        message: $t('distribution.errorIntegerTip1'),
        type: 'error',
        duration: 1500
      })
      return
    }
    if (paySettlementType.value !== 1 && dataForm.value.amountMin < 1) {
      ElMessage({
        message: $t('withdraw.errotTip1'),
        type: 'error',
        duration: 1500
      })
      return
    }
    if (paySettlementType.value !== 1 && dataForm.value.amountMax > 20000) {
      ElMessage({
        message: $t('withdraw.errorTip7'),
        type: 'error',
        duration: 1500
      })
      return
    }
    if (paySettlementType.value !== 1 && dataForm.value.amountMax < dataForm.value.amountMin) {
      ElMessage({
        message: $t('withdraw.errorTip2'),
        type: 'error',
        duration: 1500
      })
      return
    }
    if (isExpenseAmount.value && !dataForm.value.expenseAmount) {
      ElMessage({
        message: $t('distribution.decimalTip1'),
        type: 'error',
        duration: 1500
      })
      return
    }
    if (dataForm.value.autoCheck === 1) {
      if (!isExpenseNumber.value && !isProd.value && !isExpenseAmount.value) {
        ElMessage({
          message: $t('distribution.systemJudgmentTips'),
          type: 'error',
          duration: 1500
        })
        return
      }
    }
    const param = dataForm.value
    http({
      url: http.adornUrl('/platform/distributionConfig'),
      method: 'post',
      data: http.adornData(param)
    })
      .then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500
        })
      })
  })
}

/**
 * 切换选项数据初始化
 */
const changeRadio = (autoCheck) => {
  if (autoCheck === 0) {
    isProd.value = false
    dataForm.value.productVOList = []
    productVOList.value = []
    isExpenseNumber.value = false
    dataForm.value.expenseNumber = null
    isExpenseAmount.value = false
    dataForm.value.expenseAmount = null
  } else if (autoCheck === 2) {
    dataForm.value.realName = false
    dataForm.value.identityCardNumber = false
    dataForm.value.identityCardPic = false
  }
}

const prodsSelectVisible = ref(false)
const prodsSelectRef = ref(null)
/**
 * 显示添加指定商品弹框
 */
const prodsSelectHandle = () => {
  prodsSelectVisible.value = true
  nextTick(() => {
    prodsSelectRef.value?.init(productVOList.value)
  })
}

/**
 * 商品选择回调
 * @param prods
 */
const selectDistributionProds = (prods) => {
  if (prods) {
    productVOList.value = []
    for (const i in prods) {
      productVOList.value.push(prods[i])
    }
  }
}

/**
 * 删除指定商品
 * @param index
 */
const deleteProd = (index) => {
  productVOList.value.splice(index, 1)
}

/**
 * 清除消费次数数据
 */
const removeExpenseAmount = () => {
  dataForm.value.expenseAmount = null
}

/**
 * 清除消费金额数据
 */
const removeExpenseNumber = () => {
  dataForm.value.expenseNumber = null
}

/**
 * 消费次数上限校验
 */
const checkNumber = () => {
  const inNumber = Math.round(parseInt(dataForm.value.expenseNumber))
  if (inNumber < 1) {
    dataForm.value.expenseNumber = 1
  } else {
    dataForm.value.expenseNumber = inNumber > 1000 ? 1000 : inNumber
  }
}

/**
 * 消费金额校验
 * @param expenseAmount
 */
const checkAmount = (expenseAmount) => {
  if (!expenseAmount) {
    return
  }
  const inAmount = parseFloat(dataForm.value.expenseAmount).toFixed(2)
  if (inAmount < 0) {
    dataForm.value.expenseAmount = 0
  } else {
    dataForm.value.expenseAmount = inAmount > 10000 ? 10000 : inAmount
  }
}
</script>

<style scoped lang="scss">
.component-marketing-distribution-item {
  .input-checked {
    margin-right: 10px;
  }
  .marginBottom{
    margin-bottom: 10px;
  }
  .productStyle {
    margin: 5px 10px 0 68px;
    float:left
  }
  .save {
    margin-left: 50px;
  }
}
.performanceAttribution-content{
  max-width: 300px;
}
:deep(.el-form-item__content) {
  display: block;
}
.input-group {
  display: flex;
  margin-bottom: 18px;
}
</style>
